package binarytree;

/**
 * @Author: 海琳琦
 * @Date: 2022/2/22 18:08
 * https://leetcode-cn.com/problems/maximum-binary-tree/
 * 构建最大二叉树
 */
public class ConstructMaximumBinaryTree {

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    /**
     * 分割  左子树和右子树  [左闭，右开)
     * @param nums
     * @return
     */
    public static TreeNode constructMaximumBinaryTree(int[] nums) {
        return traversal(nums, 0, nums.length);
    }

    public static TreeNode traversal(int[] nums, int begin, int end) {
        if (end - begin == 0) {
            return null;
        }
        int index = begin;
        //1、找到最大值的索引，创建根结点
        for (int i = begin + 1; i < end; i++) {
            if (nums[i] > nums[index]) {
                index = i;
            }
        }
        TreeNode root = new TreeNode(nums[index]);
        if (end - begin == 1) {
            return root;
        }
        //2、分割数组 左数组和右数组
//        int leftBegin = begin;
//        int leftEnd = index;
//        int rightBegin = index + 1;
//        int rightEnd = end;
        //3、递归左子树、右子树
        root.left = traversal(nums, begin, index);
        root.right = traversal(nums, index + 1, end);
        return root;
    }

    public static void main(String[] args) {
        int [] temp ={3,2,1,6,0,5};
        TreeNode treeNode = constructMaximumBinaryTree(temp);
        System.out.println();
    }
}
